/*
* Copyright 2008 Lukas Vlcek
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.permutation;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;

public class PermutationMap extends MapReduceBase implements Mapper<LongWritable, Text, Text, Text> {

    Log log = LogFactory.getLog(PermutationMap.class);
    private Text myKey = new Text();
    private Text word = new Text();

    public void map(LongWritable key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {

        String[] oldRowData = value.toString().split("\\s");

        int nextGeneration = oldRowData.length + 1;
        String[] newRowData = new String[nextGeneration];

        for (int j = 0; j <= oldRowData.length; j++) {

            newRowData[j] = Integer.toString(nextGeneration);
            System.arraycopy(oldRowData, 0, newRowData, 0, j);
            System.arraycopy(oldRowData, j, newRowData, j + 1, oldRowData.length - j);

            word.set(arrayToString(newRowData));
            myKey.set(newRowData[0]);
            output.collect(myKey, word);
        
        }
    }

    private String arrayToString(String[] array) {
        StringBuffer sb = new StringBuffer();
        for (String s : array) {
            sb.append(s);
            sb.append(" ");
        }
        return sb.toString().trim();
    }
}
